var express = require("express");
var router = express.Router();
var fetch = require('node-fetch');
const https = require("https");
// const {base64_decode} = require('../utils/file.js');
const { v4: uuidv4 } = require('uuid');
const httpsAgent = new https.Agent({ rejectUnauthorized: false });
const { sha256, secretKey } = require("../utils/util");
const jwt = require("jsonwebtoken");
const APP_ID = 'wx2f7cb4d6eee36501';
const SECRET = '92a0600e48c41d372de7ed563557e5d5';
// 表现层，引入业务层
const userService = require("../service/userService");
/* GET users listing. */
router.get("/", function (req, res, next) {
  res.send("respond with a resource");
});
router.get('/weixinLogin',async function(req,res){
  let code = req.query.code;
  let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${APP_ID}&secret=${SECRET}&js_code=${code}&grant_type=authorization_code`;
  console.log("url",url);
  try{
    let fetchResult = await fetch(url,{
      agent: httpsAgent
      });
    let data = await fetchResult.json();
    console.log('data',url,data)
    if(!data.errcode){
      let user = await userService.usernameExist(data.openid);
      if(Object.keys(user).length > 0){
        res.send(user);
      }else{
        let newUser = await userService.createUser({username:data.openid,pwd:''});
        res.send(newUser);
      }
    }else{
      res.send({});
    }
  }catch(e){
    console.log("error:",e);
    res.send({});
  }
  
});
router.post('/weixinDetail/:id', async function(req,res){
  let id=req.params.id;
  let {nickname,image} = req.body;
  let user= await userService.findById(id);
  if(image){
    let strUUID = uuidv4();
    base64_decode(image,"./public/images/"+strUUID+".jpeg");
    user.headImg=strUUID+".jpeg";
    // res.send({nickname,image:strUUID+".jpeg"});
    // return;
  }
  if (nickname) {
    user.nickname=nickname;
  }
  await userService.updateUser(id,user);
  res.send(user);
})
/**
 * @swagger
 * /users/loginUser:
 *    post:
 *      tags:
 *      - users
 *      summary: 用户登录
 *      requestBody:
 *        required: true
 *        content:
 *          application/x-www-form-urlencoded:
 *            schema:
 *              type: object
 *              properties:
 *                username:
 *                  type: string
 *                pwd:
 *                  type: string
 *      responses:
 *        200:
 *          description: 操作成功
 *        401:
 *          description: 权限不足
 * */
// 用户登录
router.post('/loginUser', async function (req, res) {
  let { username, pwd } = req.body;
  let userData = await userService.loginUser({ username, pwd: sha256(pwd) });
  console.log(userData);
  if (userData.length > 0) {
    if (userData[0].privilege == "是") {
      console.log('登录成功');
      let token = jwt.sign({ data: userData[0] }, secretKey);
      res.send({ status: 2, token });
    } else {
      console.log("用户登录成功");
      res.send({ status: 1 });
    }
  } else {
    res.send({ status: 0 });
    console.log("密码或账号错误");
  }

});

// 注册
router.post('/reg', async function (req, res) {
  let { username, pwd } = req.body;
  let data = await userService.createUser({ username, pwd: sha256(pwd) });
  res.send(data);
});

//用户验证是否存在
router.post('/usernameExist', async function (req, res) {
  let { username } = req.body;
  console.log(username, "58行");
  let data = await userService.usernameExist(username);
  console.log('data:', data);
  if (data.length > 0) {
    res.send({
      status: 1
    });
  } else {
    res.send({
      status: 0
    });
  }
});
/**
 * @swagger
 * /users:
 *    post:
 *      tags:
 *      - users
 *      summary: 用户增加
 *      requestBody:
 *        required: true
 *        content:
 *          application/x-www-form-urlencoded:
 *            schema:
 *              type: object
 *              properties:
 *                username:
 *                  type: string
 *                pwd:
 *                  type: string
 *                nickname:
 *                  type: string
 *                address:
 *                  type: array
 *      responses:
 *        200:
 *          description: 操作成功
 *        401:
 *          description: 权限不足
 * */
//增加
router.post('/', async function (req, res) {
  console.log(req.body);
  let { username, pwd, nickname, address, privilege } = req.body;
  let data = await userService.createUser({ username, pwd: sha256(pwd), nickname, address, privilege });
  console.log("增加成功");
  res.send({ data });
});

/**
 * @swagger
 * /users/{id}:
 *    delete:
 *      tags:
 *      - users
 *      summary: 删除用户
 *      parameters:
 *      - name: id
 *        in: path
 *        description: 删除用户id
 *        required: true
 *      responses:
 *        200:
 *          description: 操作成功
 *        401:
 *          description: 权限不足
 * */
//删除
router.delete('/:id', async function (req, res) {
  let { id } = req.params;
  let data = await userService.removeUser(id);
  console.log("删除成功");
  res.send({ data });
  console.log({ data });
});
/**
 * @swagger
 * /users/find:
 *    get:
 *      summary: 根据条件查找用户
 *      tags:
 *       - users
 *      parameters:
 *      - name: type
 *        in: query
 *        description: 搜索类型
 *        required: false
 *      - name: value
 *        in: query
 *        description: 搜索值
 *        required: false
 *      - name: current
 *        in: query
 *        description: 当前页
 *        required: false
 *      - name: size
 *        in: query
 *        description: 每页显示数
 *        required: false
 *      responses:
 *        200:
 *          description: 操作成功
 *        401:
 *          description: 权限不足
 * */
//查询
router.get('/find', async function (req, res) {
  let { type, value, current, pageSize } = req.query;
  let searchObj = {};
  if (type) {
    searchObj[type] = { $regex: value };
  }
  let data = await userService.findUser(searchObj, { current: current || 1, pageSize: pageSize || 5 });
  res.send({ data });
});
/**
 * @swagger
 * /users/{id}:
 *    put:
 *      tags:
 *      - users
 *      summary: 修改用户
 *      parameters:
 *      - name: id
 *        in: path
 *        description: 用户id
 *        required: true
 *      requestBody:
 *        required: true
 *        content:
 *          application/x-www-form-urlencoded:
 *            schema:
 *              type: object
 *              properties:
 *                username:          
 *                  type: string
 *                pwd:    
 *                  type: string
 *                nickname:
 *                  type: string
 *                address:
 *                  type: string
 *      responses:
 *        200:
 *          description: 操作成功
 *        401:
 *          description: 权限不足
 * */
//查询id修改
router.get('/:id', async function (req, res) {
  let { id } = req.params;
  let data = await userService.findById(id);
  res.send({ data });
});
router.put('/:id', async function (req, res) {
  let { id } = req.params;
  let { username, pwd, nickname, address, privilege } = req.body;
  let data = await userService.updateUser(id, { username, pwd: sha256(pwd), nickname, address, privilege });
  res.send({ data });
})
module.exports = router;
